package com.xw.util;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.http.HttpUtil;
import com.google.common.collect.Maps;
import com.xw.model.sdk.WXUnifiedOrderMP;
import com.xw.sdk.wechat.WXPayUtil;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;

/**
 * 微信小程序支付工具
 */
public class WXMPPayUtils {

    public static void main(String[] args) throws Exception {
        WXUnifiedOrderMP mp = new WXUnifiedOrderMP();
        mp.setTotal_fee(100);
        mp.setBody("Mix4");
        mp.setNotify_url("http://www.sea.com");
        mp.setOut_trade_no(AppUtil.getOrderCode());
        mp.setSpbill_create_ip("127.0.0.1");
        mp.setOpenid("");

        Map unifiedorder = WXMPPayUtils.unifiedOrder(mp);
    }

    private static final String SERVER = "https://api.mch.weixin.qq.com/pay/unifiedorder";
    private static final String APPID = PropertiesUtil.getProperty("WEICHAT_APPID");
    private static final String MCHID = PropertiesUtil.getProperty("WEICHAT_MCHID");
    private static final String APIKEY = PropertiesUtil.getProperty("WEICHAT_APIKEY");

    public static Map unifiedOrder(WXUnifiedOrderMP wxUnifiedOrderMP) throws Exception {
        wxUnifiedOrderMP.setAppid(APPID);
        wxUnifiedOrderMP.setMch_id(MCHID);
        wxUnifiedOrderMP.setNonce_str(WXPayUtil.generateNonceStr());

        Map<String, Object> map = BeanUtil.beanToMap(wxUnifiedOrderMP);
        Map<String, String> mapString = Maps.newHashMap();

        for (Map.Entry<String, Object> entry : map.entrySet()) {
            //将里面的空值过滤掉
            if (entry.getValue()!=null) {
                mapString.put(entry.getKey(), entry.getValue().toString());
            }
        }
        //生成签名
        String xml = WXPayUtil.generateSignedXml(mapString, APIKEY);
        String post = HttpUtil.post(SERVER, xml);
        Map<String, String> stringMap = WXPayUtil.xmlToMap(post);
        System.err.println("小程序支付结果： " + stringMap );
        if (stringMap.get("return_code").equals("SUCCESS") && stringMap.get("result_code").equals("SUCCESS")) {
            map.put("body", stringMap);
            map.put("code", 200);
        }else{
            map.put("msg",stringMap);
            map.put("code", 101);
        }
        return map;
    }
}
